package com.lgl.handler;

import com.alibaba.fastjson.JSONObject;
import com.lgl.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;


public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    //1.定义成员变量
    //事件处理器上下文，存储handler信息，写操作
    private ChannelHandlerContext context;
    //记录服务器返回的数据
    private String result;

    private String param;

    private RpcRequest rpcRequest;

    private String serverPort;

    /** 参数类型 字符串：String Json: Json**/
    private String paramType;

    //2.实现channelActive 客户端和服务器连接时，该方法自动执行
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context = ctx;
    }

    //3.实现channelRead 当我们读到服务器数据，该方法自动执行
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //读到的数据赋值给成员变量
        result = msg.toString();

        notify();
    }

    //4.将客户端的数据写到服务器
    public synchronized Object call() throws Exception {

        context.writeAndFlush(rpcRequest);
        wait();

        long currentTime = System.currentTimeMillis();
        long sendTime = rpcRequest.getSendRpcTime();
        long rpcTime = currentTime - sendTime;
        System.out.println("服务器" + rpcRequest.getServerPort() + "耗时: " + rpcTime);
        return result;
    }

    //5.设置参数的方法
    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    public String getServerPort() {
        return serverPort;
    }

    public void setServerPort(String serverPort) {
        this.serverPort = serverPort;
    }

}
